package ch.nostromo.tiffanys.engines.tiffanys.ai;

import java.util.ArrayList;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.logging.Logger;

import ch.nostromo.tiffanys.engines.EngineResources;

public class OpeningBook {
  static Logger logger = Logger.getLogger(OpeningBook.class.getName());

  private static OpeningBook instance = null;
  private ArrayList<String> openings = null;
  private EngineResources er = null;
  private Random r = null;
  
  private OpeningBook() {
    er = new EngineResources("", "");
    r = new Random();
    loadBook();
  }
  
  private void loadBook() {
    try {
      int counter = 0;
      String openingsContent = er.loadEngineResource("opening.data");
      openings = new ArrayList<String>();
      StringTokenizer st = new StringTokenizer(openingsContent, "\n");
      while (st.hasMoreTokens()){
        openings.add(st.nextToken());
        counter ++;
      }
      logger.finer(counter + " Openings loaded.");
    } catch (Exception e) {
      logger.severe("Openingbook not found" + e.getMessage());
    }
    
  }
  
  public static OpeningBook getInstance() {
    if (instance == null) {
      instance = new OpeningBook();
    }
    return instance;
  }

  public String checkForMoves(String playedPGN) {
    ArrayList<String> foundVariants = new ArrayList<String>();
    
    // Search list
    int size = openings.size();
    for (int i = 0; i < size; i ++) {
      if (playedPGN.length() == 0 || openings.get(i).startsWith(playedPGN) && openings.get(i).length() > playedPGN.length() && openings.get(i).indexOf("O-O") > 0) {
        foundVariants.add(openings.get(i));
      }
    }

    logger.finer("Found opening variants: " + foundVariants.size());
    if (foundVariants.size() > 0) {
      int idx = r.nextInt(foundVariants.size());
      return foundVariants.get(idx);
    }
    
    return null;
  }
  
}
